<template>
  <el-upload class="avatar-uploader" accept="image/jpg,image/jpeg,image/gif,image/png" action="#" :show-file-list="false"
    :http-request="uploadAvatar" v-if="!preview">
    <img :src="avatarUrl" class="avatar" v-if="avatarUrl" />
    <el-icon class="avatar-uploader-icon" v-else>
      <el-icon-plus />
    </el-icon>
  </el-upload>
  <el-avatar shape="square" :size="150" :src="avatarUrl || noAvatar" v-else />
</template>

<script lang="ts">
export default {
  name: 'AutumnAvatar'
}
</script>

<script lang="ts" setup>
import { ref, watch } from 'vue'
import { UploadRequestOptions } from 'element-plus'
import noAvatar from 'src/assets/no_avatar.png?url'
import { $upload, $preview } from 'src/util/tools'

const props = defineProps({
  modelValue: {
    type: String,
    default: () => ''
  },
  preview: {
    type: Boolean,
    default: () => false
  }
})

const avatarUrl = ref<string>('')
const emits = defineEmits(['update:modelValue'])

//上传
const uploadAvatar = async function (e: UploadRequestOptions) {
  const params = new FormData()
  params.append('files', e.file)
  const data = await $upload(params)
  avatarUrl.value = await $preview(data[0].id)
  emits('update:modelValue', data[0].id)
}

//监听
watch(
  () => props.modelValue,
  async (newVal: string) => {
    avatarUrl.value = await $preview(newVal)
  }
)

</script>

<style lang="scss" scoped>
.avatar-uploader .el-upload {
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  border: 1px dashed #cccccc;
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}

.avatar {
  width: 150px;
  height: 150px;
  display: block;
}
</style>
